Chapter 1:
Introduction

Welcome to Intermediate Java Programming! My name is Alan Simpson, and I'll be your instructor for the next six weeks. If you took my Introduction to Java Programming course, welcome back. Here you'll build on the skills and concepts you learned in that course to move ever deeper into the world of professional-grade computer programming and app development.

By the time you finish this course, we'll have covered these topics (not necessarily in this order):

I think we'll have enough to keep us busy!

Before we jump into new ways to use Java, though, we're going to spend today reviewing the Java topics we covered in the first course. This will serve as a refresher if you took my first class. If you didn't take it, you'll see what you need to know about Java before starting this course.

Let's jump in to our Java review.

Chapter 2:
Java Review

To start with, here's an overview list of the Java topics covered in my first course. You should already be familiar with many of them.

Whew! That's quite a list! We're going to do a little more in-depth review of these topics in this lesson, but if you're unfamiliar with many of these terms and concepts, and the review doesn't refresh your memory, you might want to consider taking the first course before taking this one.

If you do recognize all these, that's great! Let's go over what they mean so we're ready to tackle the new Java concepts in this course.

Classes and Objects

A class describes some entity (thing) that we want to represent in a computer. For example, if we were writing software to support a school environment, we would need to represent the entities involved in the processes in our software. What entities would we need to represent in a school? Well, there are students, teachers, classrooms, schedules, grades, classes, and so on. Note that an entity doesn't have to be a physical thing. It can be an idea or concept, like the schedules and grades I mentioned.

When I define a class in Java, I have to tell the program what data to store about the entity, such as a student's name, address, or phone number. I also have to tell Java what the entity can do in my system. A student can register for a class, turn in assignments, get grades, and so on.

We declare data elements (or attributes) as variables in the class definition. And we declare the actions of a class as its methods. More about them in a minute.

Once we've declared a class and defined its data and actions, we can use it to create objects. Objects are individual entities of the types defined by the class. For example, in the school environment, we could create Student and Teacher classes. From those, we could create Student objects to represent the students Tom, Jane, and Bill. We could also create Teacher objects to represent the teachers Ms. Carpenter, Mr. Jones, and Ms. Smith.

These objects could then interact using their methods—to record, for example, that Tom is in Ms. Carpenter's class, Jane is in Ms. Smith's class, and Bill is in Mr. Jones' class.

Class Members

Classes have data members (also called attributes and fields) and method members (also called actions). Data members are normally instance variables in the class, or variables that are part of each instance (or object) created from the class. For example, each Student object in the example we talked about earlier would have variables in which to store a student's name, address, ID number, gender, birthday, and so on. These declarations might take this form:

        	public class Student {
    			private String firstName;
				private String lastName;
    			private String address;
    			private int studentID;
    			private Date birthDate;
    			private char gender;
   			 . . . // other declarations and methods not shown
			}
		

We usually declare instance variables as private so that no other program can manipulate them directly. Methods normally handle setting and retrieving the values in these fields.

Every Student object that we create from this class will have these fields, and each object can have its own values in the fields.

Methods and Constructors

Methods are members of the class, too. We declare these as well, usually after the variables, and most of the time we declare them as public so other programs can call them up. Method declarations also define what type of value the method will return (if any) and what information to expect as arguments when a program calls the method. We call that piece of the declaration the method'ssignature.

Method names are normally verbs that describe what the methods do. By tradition, their names start with lowercase letters, and each word in the name after the first word starts with a capital letter. For example, setFirstName() and getGender() are conventional method names.

Besides its signature, we also have to define a method's actions, and we do that in the body of the method, between the curly brackets ({}). For example, we could define methods in the Student class to manage the birthDate field like this:


        	public class Student 
            {
				. . . // variable declarations and some methods are not shown
    				public void setBirthDate(int month, int day, int year) 
                    {
        				birthDate = new Date(year, month, day);
					}
				
public Date getBirthDate() { return birthDate; } }

TQA-2 --- Constructors are special methods that we can use to construct, or initialize, new objects of the class. You can identify constructors easily; they always have the same name as the class and never have a return type. Java calls a constructor whenever a program creates an object from a class. For example, a constructor for the above Student class could look like this:


        	public Student() 
            {
    			firstName = "";
				lastName = "";
				address = "";
				studentID = 0;
				birthDate = new Date();
				. . .
			}
            
		

The last line above, which initializes the variable birthDate, also invokes another constructor, from the Date class, with the code new Date().

Primitive Data Types

Most data types we use in Java are classes, but Java does have some primitive types that we use to build all the other classes. Here are the numeric types:

Java's Numeric Types
Type Size Minimum Value Maximum Value
byte 1 byte (8 bits) -128 127
short 2 bytes (16 bits) -32,768 32,767
int 4 bytes (32 bits) -2,147,483,648 2,147,483,647
long 8 bytes (64 bits) -9,223,372,036,854,775,808 9,223,372,036,854,775,807
float 4 bytes (32 bits) ±1.4 × 10-45 ±3.4028235 × 1038
double 8 bytes (64 bits) ±4.9 × 10-324 ±1.7976931348623157 × 10308

In addition to the numeric types, Java also has two other primitive types: one for characters and one for Boolean values. A variable of the char type can hold a single character, such as A, Z, !, 9, and so on. A boolean variable holds one of two values: It must be either true or false.

Those are all the basic types that Java has. All other types are classes, including any that we write, and they're all made from the eight primitive types. They may include other classes, too; but ultimately, all classes trace their data types back to these primitives.

I hope all your Java knowledge is starting to come back to you by now!

We still have a lot to review, so let's keep going.

Chapter 3:
Parameter Passing

Parameters are what you use to give information to a method. For any method that needs information, you should define parameters in its signature, like we did with the hypothetical setBirthDate() method in the previous chapter. It needed three pieces of information, all numbers: a month, a day, and a year. The method defined these as int types. Based on that signature, anyone who wants to use this method to set the birth date for a student must provide those three integer numbers as arguments. Arguments are the actual values you put into a parameter list when you use a method.

Parameters (and thus arguments) can be any type defined in Java. That includes all the primitive types, plus any other class or type defined in a program.

Variables, Constants, and Literals

I've used the term variable several times without really defining it, so I'll do that now. In Java, a variable is a value that can change. So an int variable could refer to a value of 0, then have its value changed to -5, and then to 1,000,000. (A variable can only hold one value at a time.)

If we use the Student class from earlier to create a variable, that variable would refer to an entire object that would contain all the data fields (instance variables) in the class that hold information about a student. In that case, then, one variable would refer to an object containing other variables.

We declare variables in Java with a type and a name, and sometimes a value and an access modifier. Instance variables have an access modifier to tell Java whether a variable is public (anyone can directly access it) or private (only its own class can access it). Local variables (defined and used locally in a method) don't have an access modifier because they're always private. But we can assign values to them in their declarations.

For example, here are declarations (again) for some instance variables from our Student class:

        	
            	private String firstName;
				private int studentID;
				private Date birthDate;
			
		

In every Student object we create, these declarations will create a String object to hold a name, an int object to hold an ID number, and a Date object to hold a birth date.

You might see local variable declarations like these in a method dealing with coordinates in a graph:

        	
            	int x = 0;
				int y = 0;
			
		

In these declarations, you assign values at the same time you declare the variable instead of assigning values in a separate statement.

Variable names are normally nouns that describe what the variables contain. Java programming convention is that variables start with lowercase characters, and then we capitalize the first letter of each following word in the name, just like method names. Some conventional names are firstName, birthDate, and x (which isn't strictly descriptive, but it does have meaning when dealing with geometrical coordinates).

TQA-3 --- Constants represent values that don't change. They can be either named constants, which are often just called constants, or literals. A named constant refers to a value that doesn't change. For example, if I were to write a program that dealt with geometry and used the mathematical value π repeatedly, I could either type 3.1415927 every time I needed it, or I could set up a name for it. The name has several advantages. It's easier to remember, easier for another programmer to read and understand, and easier to use correctly. If I use a name, the compiler will insert the same value for that name every time. But if I enter the number manually every time and I accidentally type 3.1445927 once, for example, the compiler won't recognize that it's the wrong value.

Constant names, by convention, are all capital letters with underscores (_) between the words. For example, PI and MAX_SIZE are descriptive constant names.

You define named constants with the final keyword. We could define the two constant names above like this:

        	
            	final double PI = 3.14159265358979;
				final float MAX_SIZE = 1000;
			
		

Literals are constants, too, since their values can't change. But literals use their values as their names. For example, 5 is an integer literal, 2.4 is a floating-point literal, Q is a character literal, false is a Boolean literal, and "this is a String literal" is a String literal.

Console Input and Output

In Java, as in most programming languages, the console refers to the default input and output devices. The term goes back to early mainframe days when computers had a large typewriterlike device called the console that operators used to get messages and enter commands. For most of us today, the console is really two devices: our keyboard for input and our monitor for output. All console input and output is in text format.

ConsoleJava's class library makes console input and output relatively painless. Output is simplest. It requires no declarations at all; you simply use a class (System) and object (out) that are available in every Java program. Java's System class provides several useful objects and methods to us, and the out object is one of them. The out object is an output stream that defaults to your monitor. It's easy to send text output to your monitor like this:

        	
            	System.out.print("Text to display");
			
		

This statement calls the print() method of the out object in the System class to send text to the screen. It allows arguments that are strings or any of Java's primitive types, and it converts them to text and displays them on the screen.

Input from the console (keyboard) is not quite as simple, as it requires at least one declaration. The simplest input method uses Java's Scanner class, which has a number of methods to extract different types of data from an input text stream. Declaring and using the console input device as a Scanner object is easy:

        	
            	Scanner input = new Scanner(System.in);
				String s = input.nextLine();
				int i = input.nextInt();
				float f =  input.nextFloat();
			
		

The first line declares and creates a Scanner object using the default input stream. The other lines use several of the Scanner object's methods to extract different types of data from the input. You can find a complete list of its methods at Sun's Java API documentation Web site, which you'll find in this lesson's Supplementary Material.

Expressions

Java uses expressions to evaluate combinations of data items that we join with operators. You should already be familiar with arithmetic expressions and logical expressions.

Arithmetic expressions combine numeric values using standard operations like addition, subtraction, multiplication, and division. Those operators are +, -, *, and /, respectively. Remember that multiplication and division have higher priority than addition and subtraction, so they get evaluated first unless you use parentheses to specify a different priority. Here are a few arithmetic expressions as examples. You can assume that we've already declared and assigned values to all variables.

        	
            	1. 2 + 2
				2. PI * radius * radius
				3. 3 + 4 * 5
				4. (3 + 4) * 5
				5. (-b + Math.sqrt(b * b – 4 * a * c)) / (2 * a)
			
		

These are all valid expressions that give you numeric results. The first calculates a simple sum. The second gives the area of a circle. The third and fourth illustrate the priority of operations. The third does its multiplication first, then its addition, and gets a result of 23. Since the parentheses reorder the operations in the fourth example, the result is 35.

You might (or might not) recognize the last example from algebra as one of the roots of a quadratic equation. Don't worry if you didn't recognize it! It's in a different form than we're used to, and besides, algebra isn't a prerequisite for this course. I just included it to show that Java can handle expressions that are as complex as we need them to be. The Math.sqrt() call is to the square root method in the Math class, which gives us a lot of useful mathematical functions. You can find out more about them at the Java API Web site.

Logical Expressions

Logical expressions compare data values to get Boolean values. They also combine Boolean values and always give a Boolean result (either true or false). The comparison operators are equals (==), not equals (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=). The logical operators are and (&&), or (||), and not (!).

Here are some examples of logical expressions:

        	
            	1. 1 == 1
				2. 1 == 2
				3. a == b
				4. b != c
				5. c >= d
				6. (d == e) && (e < f)
				7. (f == g) || (g == h)
				8. !(h == j)
			
		

Just to make sure we cover all the bases, let me discuss each of these. The first example (1 == 1) will always give a true result. The second (1 == 2) will always be false. The third (a == b) will be true if the variables a and b have the same value and false if they don't. The fourth (b != c) will be true if b and c don't have the same value and false if they do. The fifth (c >= d) will be true if c is at least as big as d and false if c is less than d.

The sixth one, (d == e) && (e < f), requires that two conditions be true if the expression is to be true. That's how the and (&&) operator works. For the and operator to return true, both of its operands must be true. If either operand is false, && returns false. So if d and e have the same value and e's value is less than f's, the expression will be true. Otherwise, it will be false.

The seventh one, (f == g) || (g == h), will be true if either of its comparisons is true. The or operator (||) needs only one of its operands to be true in order to return a true result. So if f and g have the same value or g and h have the same value, the expression will be true. It will be false only if the three of them contain three different values.

The last expression, !(h == j), uses the not operator (!) to reverse the result of its operand. So if h and j have the same value, the expression will be false, and it will be true if they have different values.

As always, if any of these raise questions in your mind, please ask me about them in the Discussion Area.

That's one of my favorite parts of this course,
since it lets me interact with you directly
.

Chapter 4:
Making Decisions

One of my favorite quotes about decision making with computers is from two well-known computer scientists, John Hennessy and David Patterson. Dr. Hennessy is currently president of Stanford University, and Dr. Patterson is a professor and past chair of the computer science department at the University of California, Berkeley. In a textbook that they wrote together on computer architecture, they said, "What distinguishes a computer from a simple calculator is its ability to make decisions."

When you think about it, a simple calculator can do just about everything a computer can do: input data, output results, do calculations, even display graphs. But what it can't do is make decisions based on the data (unless it's one of the newer programmable calculators, of course).

In Java, we base decisions on the results of logical expressions, which we just looked at. Decisions in Java take the form of if . . . else . . . statements, where the ". . ." in each case is the logic we want to perform based on whether the condition we test is true or false. The complete format of the if statement is:

if (logical expression) {
			// statement(s) to run if the condition is true
			}
			else {
			// statement(s) to run if the condition is false
			}
		

You don't have to include all of that, though. You can leave the whole else section out if you don't want to do anything when the condition is false. You can also leave the curly brackets out if you only have one statement to execute in either case. You only have to use them for multiple lines of code. But programmers normally include them anyway, just for clarity and to make it easier to add more code later.

Repeating Actions With Loops

TQA-1 --- Java also gives us some convenient formats for repeating actions in loops. We talked about two of them in the first Java course, the while and do-while loops. Their format also includes a logical expression, which Java uses each time through the loop to decide whether to continue. So the equivalent of an if statement is hidden in each loop.

This is the while loop's format:

        while (logical expression) 
        {
			// statements to repeat while the condition is true
		}
        

TQA-1 --- This type of loop evaluates the logical expression before beginning the loop, and if the condition is true, the loop runs its internal statements. If the expression is false the first time Java evaluates it, Java may never run the loop's statements.

This is the do-while loop's format:

        do {
			// statements to repeat while the condition is true
		} while (logical expression);
        

This type of loop evaluates the logical expression after finishing each iteration of the loop, and if the condition is true, it goes back and runs the loop again. That means this loop will always execute its statements at least once before testing its condition the first time.

Java has other types of loops that are more convenient to use in certain circumstances, and we'll learn about them in this course.

Arrays

TQA-5 --- Arrays are Java's way of storing a group of similar things in one name. You could, for example, build an array of integers, an array of strings, or an array of Booleans to use in your process. It's the same concept, regardless of the type of data you store in the array. The two rules that govern arrays are (1) all elements of an array must be the same type, and (2) once you declare an array, its size is fixed and you can't change it. Java uses square brackets ([]) to designate and use arrays. Here are some array declarations and instantiations to look at:

        	int[] x;
			int[] y = new int[5];
			String[] s;
			float[] f = new float[1000];
			x = new int[10000];
			s = new String[99];
		

The first four lines declare arrays of different types; the second and fourth lines also create, or instantiate, the arrays. The fifth and sixth lines create arrays for the other two declarations.

Using an array's name by itself, like x or s above, refers to the entire array. Following the name with a number in brackets indicates a single element of the array. The references x[22] and s[0], for example, refer to a single integer and string, respectively.

And as the last example reinforces, Java uses zero-based arrays. That means that the reference s[0] gets the first string in the s array, and x[22] gets the 23rd integer in the x array.

Java doesn't do well with invalid array indexes. If I use a negative number or a value that's too large as an index, my program will blow up in my face (so to speak). One of the most common array errors is to try to refer to the last element of an array using its size. For example, if I used s[99] in a program after creating the string array above, my program would crash because 99 is the size of the array, so its largest valid index is 98.

We'll talk more about arrays in this course, too, so don't worry if the concept is a bit fuzzy right now.

Catching Errors (Exceptions)

When Java encounters an error during runtime that it can't handle, it throws an exception. That's Java terminology for blowing up your program. Unless your code catches the exception and processes it, your program won't work.

The general form for exception handling is to put the code that might throw the exception into a try block and put the code to process the exception into a catch block. For example, a common error happens when the program reads something other than a number from an input source when the program expects a number. If that occurs in a Scanner class method, an InputMismatchException gets generated.

Here's a simple try-catch mechanism to take care of that error:

        	Scanner in = new Scanner(System.in)
			try 
            {
				int num = in.nextInt();
			}
			catch (InputMismatchException e) 
            {
				System.out.println("Invalid input – not a number");
			}
		

Enumerations

Java allows us to define data types, including the values that the type can hold (its domain), by using an enumeration. An enumeration is a way to define both a data type and all the possible values it can hold. Its name is often shortened to enum, which is the keyword used to define it.

A common use of enumerations is for types that have small domains, and a common example is the days of the week. I can set up an enumeration like this:

        	public enum Day 
            {
     			SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
     			THURSDAY, FRIDAY, SATURDAY  
			}
		

Once an enumeration is declared, I can use it and its values like this:

			Day dayOfTheWeek;
			. . .
			dayOfTheWeek = Day.MONDAY;
			. . .
			if (dayOfTheWeek == Day.SUNDAY)
			. . .
		

You can find more about how to use enumerations using the link to Oracle's tutorial in the Supplementary Material at the end of the lesson.

Switch

The last review topic I'll go over here is Java's switch statement, which can replace a number of if-else statements with a single control structure if the data being tested is one of Java's primitive types, a String, or an enumeration. Here's a short example showing how we could test an integer variable named month and set up a String with an appropriate month name:

        switch (month) 
        {
			case 1:  monthString = "January";
				break;
			case 2:  monthString = "February";
				break;
		    case 3:  monthString = "March";
				break;
			case 4:  monthString = "April";
				break;             
			case 5:  monthString = "May";
				break;
			case 6:  monthString = "June";
				break;
			case 7:  monthString = "July";
				break;
			case 8:  monthString = "August";
				break;
			case 9:  monthString = "September";
				break;
			case 10: monthString = "October";
				break;
			case 11: monthString = "November";
				break;
			case 12: monthString = "December";
				break;
			default: monthString = "Invalid month";
				break;
		}
		

I think I've probably done enough of a review for you by now.
There's just one short item in Chapter 5 before we quit.


Chapter 5:
Development Environments

Before we wrap up this lesson, let me just say a word or two about development environments. In my first course, we used the BlueJ environment to provide a text editor, a visual interface, and convenient ways to create classes as well as compile and run both programs and applets. If you took that course and like BlueJ, feel free to continue using it. If you didn't take the course and would like to investigate BlueJ, you can find a link to it in the Supplementary Material for this lesson.

You can also check out some of the other environments that work equally well. Oracle provides the popular NetBeans. Eclipse and IntelliJ IDEA are other popular ones. These are full-featured integrated development environments (IDEs) that lots of professional programmers use. They're great, but they have a lot of features we don't really need for the level of programming we'll be doing in this course. And they can take some time to learn to use.

In the middle ground, there are some simple IDEs designed for a student environment. BlueJ is one of those, as is DrJava. They provide editors, simple visual interfaces, and a few debugging tools.

At the simplest level, there are several text editors that provide Java compile and run options, either built-in or as add-ons. Three that I've checked out and like are ConTEXT, jGRASP, and TextPad. Links for all of them (as well as for the IDEs) are in this lesson's Supplementary Material.

That's about all I'm going to say about your development environment. If you've done enough programming to be ready for this class, you should be able to compile and run stand-alone programs and applets without any hand-holding. If you have any difficulties, feel free to let me know and I'll try to help sort them out. You can also try out and use any (or all) of the environments I mentioned. If you prefer a plain text editor and a command-line environment, that's fine, too!

From here on out, I'll assume you can compile and run anything we write so we don't waste our limited time going over the compilation process or how to run a program.

Pick your environment, and let's jump in!

Summary

That wraps up our introduction and review. (Finally!) I know we covered an awful lot for one lesson. These are tools we'll use over and over again as we progress with Java, so I want to make sure we're all on the same page to start with.

In Lesson 2, we'll start looking a little deeper into some of Java's topics, like arrays and loops, and how we can use them together to make our lives as programmers a lot easier.

If you have any questions or thoughts to share, please post them in the Discussion Area. To get there, click the Discussion link at the top or bottom of any page in the classroom. I'll talk to you soon!

Next Steps

To finish the lesson, you'll need to complete the steps outlined below. Simply click "Next Up" at the bottom of the page to access the next activity. Or, if you wish to skip around, click the Book Icon in the top-right corner. There you'll find links to all the activities in this lesson. Here are your remaining activities:

Check out the FAQs. Since learning something new usually raises questions, every lesson in this course comes with an FAQs section.

Browse the Supplementary Material section. Here you'll find links to helpful online resources relating to the lesson.

Do the assignment. Get some hands-on practice applying what you've just learned.

Take the quiz. Reinforce what you learned with a short five-question quiz.

Participate in the Discussion Area. Ask questions about anything that came up in the lesson, and share your insights. This is where we'll create a learning community.

Additional Resources

In addition, there are some additional resources you may find helpful throughout the course. Access these resources by clicking the link for Resources listed after Lesson 12. There you'll find:

Recommended books and resources. This is a list of books and other resources that you can consult to extend your learning.

Lesson 1 Assignment

Since this is an intermediate course with lots of hands-on, in this assignment I just want to make sure you can already write, compile, and run Java programs using BlueJ or an editor of your choosing. It can be a simple HelloWorld program, using exactly this code:

        	public class HelloWorld 
            {

			    public static void main(String[] args) 
                {

        			System.out.println("Hello, world!");

    			} 
                	// End main

			} 
            // End HelloWorld
		

I just want you to go through the steps to make sure you remember how. You can use the video below as a guide on how to create and run the program in case you need a refresher.

If you need to check your Java version (on a Mac), or download the JDK (for Windows), see the Lesson Videos in the Lesson 1 Discussion area. You can use those same videos to download the BlueJ editor as well, if case you no longer have that.

Chapter 1, Video 1: "Java programs using BlueJ"

Hey, it's Alan. Welcome back. In this assignment, I just want to make sure you remember how to write and compile and run BlueJ apps. So I gave you a simple assignment of just doing a -- a simple HelloWorld app. And in this video I'll show you step by step exactly how to do that to refresh your memory. I'm doing this in Windows, but it should be the same on a Mac basically. Go ahead and open BlueJ, which you probably still have from the last course. And when you get there, click Project, New Project, and let's name this one HelloWorld. And let's put it on the desktop. But -- oh, you can put it wherever you want. It's just a working example. But I'll put it on the desktop. Click OK. All right? Now I'll move this window so you can see that there's that folder I just created. Now we'll make a little app, a little class. So click New Class. Name it HelloWorld. Keep everything else the same. Click OK. All right. So there it is. Double click that to go to the editor, and now you can replace all this code with the little bit of code I showed you in the lesson. I've got that open over in another window, so I'll just go, copy it from there, and paste it into this little code editor. And then click Close to close that. We don't need to make any changes. Very simple little app. The diagonal stripes mean it's not compiled yet. So you can right-click right on the HelloWorld thing and choose Compile. Or click it once to make sure it's selected and then click Compile over here. When you see Compiling-Done and most of the stripes have gone away, you can right-click and choose Void Main String args. If you don't see a pair of curly braces in there, type them in. Click OK. And it runs and just shows HelloWorld. Not much of a program, but all I want to do here is make sure you remember those steps. And if you got through that, you can close everything up. And come on over to Lesson 2 and we'll start writing some real code.


Lesson 1 Quiz Answers

1. What is an IDE?
An integrated development environment that speeds up Java programming by providing development and debugging tools.

2. What is a Java class?
Programming construct that represents a real-world entity and contains the data and actions related to that entity.

3. What is a Java method?
An action that an object in Java can perform.

4. Which of these is a valid Java literal?
"ABC"

5. What type of value does a logical expression in Java return?
A Boolean.


Lesson 1 Supplementary Materials